# encoding:utf-8
# @author='dapeng',
# @version='1.0.0'
import requests
from requests.exceptions import RequestException
import urllib.parse
import urllib.request
import re
import os
from voice import gettoken

headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"}


dict = {'小云':'xiaoyun','小刚':'xiaogang','若兮':'ruoxi','思琪':'siqi',
        '思佳':'sijia','思诚':'sicheng','艾琪':'aiqi','艾佳':'aijia',
        '艾诚':'aicheng','艾达':'aida','宁儿':'ninger','瑞琳':'ruilin',
        '思悦':'siyue','艾雅':'aiya','艾夏':'aixia','艾美':'aimei',
        '艾雨':'aiyu','艾悦':'aiyue','艾婧':'aijing','小美':'xiaomei',
        '艾娜':'aina','伊娜':'yina','思婧':'sijing','思彤':'sitong',
        '小北':'xiaobei','艾彤':'aitong','艾薇':'aiwei','艾宝':'aibao',
        'Harry':'harry','Abby':'abby','Andy':'andy','Eric':'eric',
        'Emily':'emily', 'Luna':'luna', 'Luca':'luca', 'Wendy':'wendy',
        'William':'william', 'Olivia':'olivia', '姗姗':'shanshan',
        '小玥':'chuangirl', 'Lydia':'lydia', '艾硕':'aishuo',
        '青青':'qingqing', '翠姐':'cuijie', '小泽':'xiaoze',
        '智香':'tomoka', '智也':'tomoya', 'Annie':'annie', 'Indah':'indah',
        '桃子':'taozi', '柜姐':'guijie', 'Stella':'stella', 'Stanley':'stanley',
        'Kenny':'kenny', 'Rosa':'rosa', 'Farah':'farah', '马树':'mashu',
        '小仙':'xiaoxian', '悦儿':'yuer', '猫小美':'maoxiaomei',  '艾飞':'aifei',
        '亚群':'yaqun', '巧薇':'qiaowei', '大虎':'dahu', 'ava':'ava'}



#请求语音接口
def request_url(url, name):
    response = requests.get(url, headers=headers)
    print('状态码: ' ,response.status_code)
    try:
        if response.status_code == 200:
            download_voice(url, name)
        return None
    except RequestException:
        return None


#下载语音
def download_voice(url, name):
    if not os.path.exists('D:/audioFiles'):
        os.makedirs('D:/audioFiles')
    file_path = r'D:/audioFiles/{}.mp3'.format(name)
    print('正在下载:', name, '.mp3\n')
    urllib.request.urlretrieve(url, file_path)


def not_empty(s):
    return s and s.strip()


def cut_text(text, length):
    text = re.sub('[\r\n\t]', '', text)
    text_array = list(filter(not_empty, text.split('。')))
    text_i = [0]
    text_len = 0
    list_1 = []
    for i in range(len(text_array)):
        list_1.append(i)
        text_len = text_len + len(text_array[i])
        # print(text_len)
        if text_len > length:
            text_len = 0
            text_len = text_len + len(text_array[i])
            # print(text_len)
            text_i.append(i-1)
            list_1.clear()

    if text_i[-1] < (len(text_array) -1):
        text_i.append(len(text_array) -1)

    # print(text_i)
    new_text_i = []
    for i in range(len(text_i) - 1):
        list1 = []
        for a in range(text_i[i] + 1, text_i[i+1] + 1):
            list1.append(a)
        new_text_i.append(list1)
    new_text_i[0].insert(0, 0)
    # print(new_text_i)

    new_text_array = []
    for t in new_text_i:
        x = ''
        for t1 in range(len(t)):
            x += text_array[t[t1]] + '。'
        new_text_array.append(x)

    return new_text_array


def get_voice(appkey, token, voice, speech_rate, format, volume, file_name, text, id):
    url = 'https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts?appkey=' + appkey \
          + '&token=' + token + '&format=' + format + '&voice=' + voice + '&speech_rate=' + \
          str(speech_rate) + '&volume=' + str(volume) + '&text=' + text
    request_url(url, file_name + str(id))


def get_network():
    response = requests.get('https://www.baidu.com')
    return response.status_code


def get_token_expire(appkey, token):
    url = 'https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts?appkey=' + appkey + '&token=' + token + '&text=你好'
    response = requests.get(url, headers=headers)
    return response.status_code


def compose(appkey, token, voice, speech_rate, format, volume, file_name, text):
    if get_network() == 200:
        res = get_token_expire(appkey, token)
        if res != 400:
            if len(text) < 300:
                get_voice(appkey, token, voice, speech_rate, format, volume, file_name, urllib.parse.quote(text), 0)
            else:
                text_array = cut_text(text, 300)
                # print(text_array)
                for id in range(len(text_array)):
                    get_voice(appkey, token, voice, speech_rate, format, volume, file_name, urllib.parse.quote(text_array[id]), id)
            return 'success'
        else:
            return 'token expired'

    else:
        return 'network fail'

def say(voice, text):
    appkey = 'gzqapkf5PzcORANO'
    token = gettoken.gettoken()
    speech_rate = -400
    format = 'mp3'
    volume = 100
    file_name = 'audio'
    compose(appkey, token, voice, speech_rate, format, volume, file_name, text)
    return 'D:/audioFiles/audio0.mp3'

def getvoice(voice):
    return dict.get(voice)

def saytail():
    return '''
    =====声音选项=====
    小云	   小刚     Indah	艾婧	    艾达	    Lydia	马树	    艾薇
    若兮	   Luna    桃子	    小美	    宁儿	    艾硕	    小仙	    艾宝
    思琪	   Luca	   柜姐	    艾娜	    瑞琳	    青青	    悦儿	    Harry
    思佳	   Wendy   Stella	伊娜	    思悦	    翠姐	    猫小美	Abby
    思诚	   William Stanley  思婧	    艾雅	    小泽	    艾飞	    Andy
    艾琪	   Olivia  Kenny	思彤	    艾夏	    智香	    亚群	    Eric
    艾佳	   姗姗	   Rosa	    小北	    艾美	    智也	    巧薇	    Emily
    艾诚	   小玥     Farah	艾彤	    艾雨	    Annie	大虎	    ava
    艾悦	   佳佳						
    '''
